package qt

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"iot-base/auth/config"
	Log "iot-base/auth/logger"
	types2 "iot-base/auth/types"
	"sort"
)

type handler func(bytes []byte) (interface{}, int)

var actions = map[string]handler{
	"move":        Move,
	"stop":        Stop,
	"GetPresets":  GetPresets,
	"SetPresets":  SetPresets,
	"GoToPresets": GoToPresets,
}

func Api(c *gin.Context) {
	resp := types2.NewResult(c)
	data := make(map[string]string)
	b, err := c.GetRawData()
	fmt.Println("请求参数:", string(b))
	Log.Log.Info("请求参数:", string(b))
	err = json.Unmarshal(b, &data)
	if err != nil {
		fmt.Println(err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	action, ok := data["action"]
	if !ok {
		resp.ErrorCode(types2.ActionNotFound, "")
		return
	}

	var sign string
	if _, ok := data["sign"]; !ok {
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	sign = data["sign"]
	delete(data, "sign")
	keys := make([]string, 0, len(data))
	for k := range data {
		keys = append(keys, k)
	}

	sort.Strings(keys) //排序字符串
	if checkSignature(keys, data) != sign {
		resp.ErrorCode(types2.SignatureError, "")
		return
	}
	if f, ok := actions[action]; ok {
		result, errCode := f(b)
		if errCode != types2.Success {
			resp.ErrorCode(errCode, "")
			return
		}
		resp.Success(result)
	}
	return
}

func checkSignature(keys []string, param map[string]string) string {
	var str string
	for _, v := range keys {
		str += v + "=" + param[v] + "&"
	}
	str += "key=" + config.Conf.Qt.Key
	fmt.Println("签名key", str)
	Log.Log.Info("签名key", str)
	has := md5.Sum([]byte(str))
	Log.Log.Infof("md5 key:%x \n", has)
	fmt.Printf("md5 key:%x \n", has)
	return fmt.Sprintf("%x", has)
}
